/* Copyright 2014 Jan Wolter */

#include "stack.h"
#include "stock.h"
#include "found.h"
#include "waste.h"
#include "solve.h"
#include "game.h"

char *gamename= "Captive Queens";
char *gameopt= "";
Stack *gathered= NULL;
Stack *temp= NULL;

int nplayed= 0;
int nwon= 0;

void setopt(char c) {}

int f1passes, f2passes;

/* This is the main program for setting up the current game */
void exec(int gather, int a)
{
    Stack *deck;
    /* Could set things like ndeck, nsuit here */
    ndeck= 2;
    npip= 11;

    /* Build and shuffle the deck */
    if (gathered != NULL && a > 1)
    {
	/* Riffle shuffle previously gathered deck */
	deck= allocStack(ncard);
	if (!temp) temp= allocStack(ncard);
	riffle(gathered, temp, a);
	cut(temp, deck);
    }
    else
	deck= shuffle();

    /* Create the foundations */
    for (int s= 0; s < nsuit; s++)
    {
	makeFound(11, s, -1, 6);
	makeFound(11, s, -1, 6);
	makeFound(1, s, +1, 5);
	makeFound(1, s, +1, 5);
    }
    f1passes= f2passes= 0;

    /* Create the waste */
    makeWaste();

    /* Create the stock */
    makeStock(DT_WASTE, 1,3,deck);

    freeStack(deck);

    if (verbose > 0) printState();

    int win= solve();
    nplayed++;
    if (win) nwon++;

    printf("Kings=%d Aces=%d Left=%d\n",
	    f1passes, f2passes, stacks[waste[0].id].n);

    /* If the gather flag is true, pick up cards in the order they lay */
    if (gather)
    {
	if (gathered == NULL)
	    gathered= allocStack(ncard);
	else
	    gathered->n= 0;

	/* Don't need to gather the stock because it is always empty */
	gatherFound(gathered);
	gatherWaste(gathered, 0);
    }

    cleanFound();
    cleanWaste();
    cleanStock();
    cleanStacks();
}

void printState()
{
    printStock();
    printWaste();
    printFound();
}

/* Is the kth foundation set done?
 *   k=0 queens
 *   k=1 fives
 *   k=2 sixes
 */
int fdone(int k)
{
    for (int i= k; i < 12; i+= 3)
	if (stacks[foundation[i].id].n < foundation[i].maxsize)
	    return 0;
    return 1;
}

int victory()
{
    if (f1passes == 0 && fdone(0)) f1passes= passcnt;
    if (f2passes == 0 && fdone(1)) f2passes= passcnt;
    return (nOff() == ncard);
}

void summary()
{
    printf("Played:    %d games\n",nplayed);
    printf("Won:       %d games (%.2f%)\n",nwon,(float)nwon*100/nplayed);
}
